package com.dji.compose_learning.producestate

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Warning
import androidx.compose.runtime.Composable
import androidx.compose.runtime.*
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext

val imagesList = listOf(
    "https://img2.baidu.com/it/u=1979633876,2912484447&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500",
    "https://img2.51tietu.net/2019/weimeitpian/20190710/1545792805101433.jpg",
    "https://img1.baidu.com/it/u=1960110688,1786190632&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281"
    )

/**
 * 这里producestate的作用是将一个请求结果包装成对应的状态值对象
 * 点击时索引状态会发生改变但是这个所以状态的改变后首先要通过网络请求重新获取新的图片，
 * 获取的图片并不是一个状态值，所以不会使函数重组而刷新页面，这里就需要通过producesstate将我们的非状态值转换成
 * 状态值从而实现重组
 */
@Composable
fun loadNetworkImage(url: String, imageRepository: ImageRepository): State<Result<Image>> {
    return produceState(initialValue = Result.Loading as Result<Image>, url, imageRepository) {
        Log.d("buobao", "thread:${Thread.currentThread().name}")
        val image = imageRepository.load(url)
        value = if (image == null) {
            Result.Error
        } else {
            Result.Success(image)
        }
    }
}

@Composable
fun ProduceStateView() {
    var imgIndex by rememberSaveable {
        mutableStateOf(0)
    }
    val imageRepository = ImageRepository(LocalContext.current)
    val result = loadNetworkImage(url = imagesList[imgIndex], imageRepository = imageRepository)

    Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
        Column {
            Button(onClick = {
                imgIndex = (imgIndex + 1) % imagesList.size
            }) {
                Text(text = "选择第${imgIndex}张图片")
            }

            when (result.value) {
                is Result.Success -> {
                    Image(bitmap = (result.value as Result.Success).image.imageBitmap, contentDescription = "")
                }
                is Result.Error -> {
                    Image(imageVector = Icons.Default.Warning,contentDescription="")
                }
                is Result.Loading ->{
                    CircularProgressIndicator() //进度条
                }
            }
        }
    }
}




















